//
//  NetworkAutoCancelModel.m
//  NetworkDemo
//
//  Created by 万孟超 on 2021/9/7.
//

#import "NetworkAutoCancelModel.h"

@interface NetworkAutoCancelModel()

//正在进行中的网络请求数组
@property (nonatomic, strong) NSMutableArray<NetworkEngine *> *networkEngines;

@end

@implementation NetworkAutoCancelModel

/*
 对象销毁时遍历当前对象持有的正在进行中的网络请求
 然后逐一手动取消
 */
- (void)dealloc {
    [self.networkEngines enumerateObjectsUsingBlock:^(NetworkEngine * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj cancelNetwork];
    }];
    [self.networkEngines removeAllObjects];
    self.networkEngines = nil;
}

/// 添加请求
/// @param engine 请求引擎
- (void)addEngine:(NetworkEngine * __nullable)engine {
    if (engine) {
        [self.networkEngines addObject:engine];
        NSLog(@"请求和类绑定%@",engine);
    }
}
/// 移除请求
/// @param engine 请求引擎
- (void)removeEngine:(NetworkEngine * __nullable)engine {
    if (engine) {
        [self.networkEngines removeObject:engine];
        NSLog(@"请求和类绑定移除%@",engine);
    }
}

#pragma mark -- Getter --

- (NSMutableArray<NetworkEngine *> *)networkEngines {
    if (!_networkEngines) {
        _networkEngines = [[NSMutableArray alloc] init];
    }
    return _networkEngines;
}

@end
